package com.study.lxy.netty.bio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class SimpleClient {
    private static final Logger logger = LoggerFactory.getLogger(SimpleClient.class);
    private static final AtomicInteger count = new AtomicInteger(0);
    public static void main(String[] args) throws Exception {
        int times = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(times);
        for (int i = 0; i < times; i++) {
            new Thread() {
                @Override
                public void run() {
                    int port = 8080;
                    Socket socket = null;
                    BufferedReader br = null;
                    PrintWriter pw = null;
                    try {
                        socket = new Socket("127.0.0.1", port);
                        pw = new PrintWriter(socket.getOutputStream(), true);
                        int currentVal = count.incrementAndGet();
                        logger.info("message send : {}", "liuxingyi" + currentVal);
                        pw.println("liuxingyi" + currentVal);
                        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String line = br.readLine();
                        logger.info("message received : {}", line);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (socket != null) {
                                socket.close();
                            }

                            if (br != null) {
                                br.close();
                            }

                            if (pw != null) {
                                pw.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        countDownLatch.countDown();
                    }
                }
            }.start();
        }
        countDownLatch.await();
        logger.info("done....");

    }
}
